/**
* @description: 工单详情 
* @author: oahcoay
* @date:
**/
<template>
  <div class="perform-task-main">
    <nav-bar class="header" back title="工单详情" @goBack="goBack"/>
    <van-cell :title="detailInfo.operName +'领取的作业工单'"  :label="detailInfo.receiveTime" class="task-head" >
      <template #right-icon>
        
        <view class="status" style="color:#00BFBF;" v-if="detailInfo.taskState==99">已完成</view>
        <view class="status" style="color:#D9001B;" v-else>未完成</view>
      </template>
    </van-cell>
    <view class="main-container">
      <plateTitle title="工单详情" class="plate-title"/>
      <view class="task-info-container">
        <van-cell-group>
          <van-cell v-for="(item,index) in taskInfoData" :key="index" :title="item.title" :value="item.value" />
        </van-cell-group>
      </view>

      <template  v-if="taskState == 99">
        <plateTitle title="工单执行" class="plate-title"/>

        <view v-for="(item, index) in executeData" :key="index" >
          <van-row type="flex" justify="space-between" class="item-title mb20">
            <van-col span="12">{{item.executeName}}</van-col>
          </van-row>
          <div class="work-content" v-for="(v, i) in item.executionTerm" :key="i">
            <!-- 执行照片 -->
            <view class="info-container">
              <van-row type="flex" justify="space-between" class="mb20" v-if="v.executionFileEntity.length>0">
                <van-col span="6">现场照片</van-col>
              </van-row>
              <div class="image-wrap">
                <div class="image-list">
                  <!-- {{v.executionFileEntity[0]}} -->
                  <div
                    class="upload-button"
                    v-for="(imgItem, imgIndex) in v.executionFileEntity"
                    :key="imgIndex"
                    :style="{'background-image': `url(${bgImg})`}"
                    @click.stop="imageHandle(imgItem, imgIndex, 'CHOOSE', [index, i, imgIndex])"
                  >
                  
                    <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgItem, imgIndex, 'PREVIEW', [index, i, imgIndex])">
                  </div>
                </div>
              </div>

              <van-divider dashed/>
              <!-- 备注 -->
              <view class="mb20">备注</view>
              <div class="remark-wrap">
                <textarea class="remark-text" v-model="v.notes" placeholder="" disabled>
                </textarea>
              </div>

            </view>

          </div>
        </view>
    
      </template>
    </view>
    

  

    <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
      <van-swipe v-if="currentImgIndex.length>0">
        <div v-for="(image, index) in executeData[currentImgIndex[0]].executionTerm[currentImgIndex[1]].executionFileEntity" :key="index">
          <van-swipe-item v-if="image.img" style="text-align: center;">
            <!-- <div style="width: 100%; text-align: center;">{{ image.previewName }}</div> -->
            <img :src="image.img" />
          </van-swipe-item>
        </div>
      </van-swipe>
    </van-popup>
  </div>
</template>
<script>
import config from "../../../common/config";

import navBar from "../../../components/common/nav-bar";
import plateTitle from '../../../components/business/plateTitle.vue';

import moment from "moment";
import axios from "axios";
import {Dialog, Toast} from "vant";
import {mapGetters} from "vuex";
import { merge } from "lodash";




const fileTemplate = [
  {
    name: "OTHER.jpg",
    // previewName: "其他照片",
    // type: "OTHER",
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
];
export default {
  name: "taskDetail",
  components: {navBar, plateTitle},
  props: {},
  data() {
    return {
      baseUrl: '', // 基础url
      taskName: '',
      siteName: '',
      tmsTim: '',
      curObjId: '',
      inletType: 1,
      taskState: 2,
      // executionClass: [],
      files: fileTemplate, // 照片map
      executeData: [
        {
          executeName: '封堵',
          isRequired: true,
          executionTerm: [
            {
              executionFileEntity: fileTemplate,
              notes: '',
            }
          ]
        },
        {
          executeName: '光缆',
          isRequired: false,
          executionTerm: [
            {
              executionFileEntity: fileTemplate,
              notes: '',
            }
          ]
        },
        {
          executeName: '遗留隐患处置',
          isRequired: false,
          executionTerm: []
        },
        {
          executeName: '通信设备',
          isRequired: false,
          executionTerm: []
        },
        {
          executeName: '动环设备',
          isRequired: false,
          executionTerm: []
        },
      ],
      delList: [], // 被删除的列表，需要和后台交互
      showPreview: false,
      originFlag: false,

      detailInfo: {},
      stateArr: {
        1: '待领取',
        2: '未执行', 
        3: '执行中', 
        99: '已完结'
      },

      currentImgIndex: [],
      bgImg: require("../../../static/img/bg_qita.png"),
			imgBase64: ''

    };
  },
  computed: {
    ...mapGetters(["userData"]),
    taskInfoData:function() {
      return [
        {
          title: "工单名称",
          value:  this.taskName
        },
        {
          title: "巡视站点",
          value: this.siteName
        },
        {
          title: "计划巡视时间",
          value: this.tmsTim
        },
      ]
    }
  },
  watch: {},
  mounted() {
  
  },
  onLoad(options) {
    this.originFlag = options.origin&&options.origin=='mine'?true:false
    config.getOptions.then(res => {
      this.baseUrl = res.firstUrl;
    })
    this.curObjId = options.objId
    this.inletType = options.inletType
    this.$apiRequest.qjqcApi.getAutumnInspectionTaskDetailsInfo({objId: options.objId, inletType: options.inletType}).then(res => {
      this.taskName = res.data.name
      this.siteName = res.data.taskSiteName
      let startTime = res.data.tmsStartTim?moment(res.data.tmsStartTim).format("YYYY-MM-DD"):null
      let endTime = res.data.tmsEndTim? moment(res.data.tmsEndTim).format("YYYY-MM-DD"):null
      this.tmsTim =  startTime+'~'+endTime
      this.taskState = res.data.taskState

      // 详细信息  
      this.detailInfo = res.data 

      this.executeData = JSON.parse(JSON.stringify(res.data.executionClass))
      this.executeData.forEach((item, index)=>{
        item.executionTerm.forEach((item1, index1)=>{
          item1.executionFileEntity.forEach((item2, index2, arr2)=>{
            arr2[index2] = Object.assign({},item2, {
              img: this.baseUrl + item2.furl,
              raw: null,
              name: item2.wjmc,
            })
          })
          
        })
      })
      // this.executeData = res.date.executionClass
    });
  },
  // 组件销毁后清空填写内容（将填写内容初始化为空）
  beforeDestroy() {
  },
  methods: {
    goSave(){
      this.handleSubmit(0)
    },
    goSubmit(){
      Dialog.confirm({
        title: '是否确认提交？',
        message: '注：提交后不可再次编辑，请确认提交内容',
        confirmButtonColor: "#417adc"
      }).then(() => {
        this.handleSubmit(1)
      })
    },
    handleSubmit(type){
      var formData = new FormData()
      formData.append(`userId`, this.userData.userId )
      formData.append(`submitType`, type)  // 提交类型 （0：暂存，1：提交）
      formData.append(`taskId`,  this.curObjId )
      this.executeData.forEach((item, index)=>{
        item.executionTerm.forEach((item1, index1)=>{
          formData.append(`executionClassEntity[${index}].executionTerm[${index1}].notes`, item1.notes )
          formData.append(`executionClassEntity[${index}].executionTerm[${index1}].executeType`, item.code)
          item1.objId&&formData.append(`executionClassEntity[${index}].executionTerm[${index1}].objId`, item1.objId)
          item1.executionFileEntity.forEach((item2, index2, arr2)=>{
            if (item2.img) {
              if (item2.raw) {
                formData.append(`executionClassEntity[${index}].executionTerm[${index1}].executionFileEntity[${index2}].file`, item2.raw)
              } else {
                formData.append(`executionClassEntity[${index}].executionTerm[${index1}].executionFileEntity[${index2}].objId`, item2.objId)
              }
            }
           
          })
        })

      })

      let config = {
		    headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: uni.getStorageSync('token') || ''
        }
		  }
		  let url = ''
		  // #ifndef IGW
		  url = '/ap/txksh/kosinManage/rest/api/autumn/submitAutumTaskInfo'
		  // #endif
		  // #ifdef IGW
		  url = `${this.baseUrl}/txksh/kosinManage/rest/api/autumn/submitAutumTaskInfo`
		  // url = `http://10.0.1.18:18001/txksh/kosinManage/rest/api/autumn/submitAutumTaskInfo`
		  // #endif

		  axios.post(url, formData, config).then(res => {
		    Toast.clear()
		    if (res.data.code == 0) {
          if (type==0) {
            Dialog.alert({
              message: '保存成功',
              theme: 'round-button',
            });
          } else {
		        Toast('提交成功')
          }
		      uni.navigateTo({
		        url: `/pages/acceptanceVersion/taskList/index`
		      })
		    } else {
		      Toast.clear()
		      Toast(res.data.msg)
		    }
		  })
      
    },
   
  
    goBack() {
      
      if(this.inletType == 1) {
        // 返回待办列表
        uni.navigateTo({
          url: `/pages/acceptanceVersion/taskList/index?status=finish&origin=${this.originFlag?'mine':''}`
        });
      } else {
        // 返回监控列表
        uni.navigateTo({
          url: "/pages/acceptanceVersion/taskMonitor/index"
        });
      }
    
    },
   
    imageHandle (imgItem, imgIndex, handleType, i) {
      this.currentImgIndex = i

      if (handleType === 'CHOOSE') {
        this.choosePhoto1(imgItem, imgIndex);
      } else if (handleType === 'PREVIEW') {
        this.showPreview = true;
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          message: `是否确认删除该照片`
        })
          .then(() => {
            if(imgItem.objId) {
              this.$apiRequest.qjqcApi.deleteFileInfo({objId: imgItem.objId}).then(res=>{
                if (res.data.code == 0){
                  Toast('删除成功！')
                  this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity.splice(this.currentImgIndex[2], 1);
                } else {
                  Toast.clear()
                  Toast(res.data.msg)
                }
              })
            } else {
              Toast('删除成功！')
              this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity.splice(this.currentImgIndex[2], 1);
            }
            
          })
          .catch(() => {
            // on cancel
          })
      }
    },
    choosePhoto1(imgItem, imgIndex) {

      const photoName = `${new Date().getTime()}`
      merge(this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity[this.currentImgIndex[2]], {
        img: this.imgBase64,
        raw: this.dataURLtoFile(this.imgBase64,`${photoName}.jpeg`),
      })

      let listArr = this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity
      if (listArr.length < 6&& listArr[listArr.length-1].img) {  // 最多上传9张 不够添加空对象
        this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity.push({
          img: '',
          raw: null,
          name: '',
        })
      }
      
    },
    choosePhoto(imgItem, imgIndex) {
      let _this = this;
      wx.chooseImage({
        count: 3,
        sourceType: ['album','camera'],
        success: (chooseImageRes) => {
          wx.getLocalImgData({
            localId: chooseImageRes.localIds[0].toString(),
            success: function (res) {
                const localData = res.localData;
                let imageBase64 = '';
                if (localData.indexOf('data:image') == 0) {
                    //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                    imageBase64 = localData;
                } else {
                    //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                    //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                    imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
                }
                
                // _this.$set(_this.files, imgIndex, merge(_this.files[imgIndex], {
                //    raw: _this.h5_url_to_blob(imageBase64),
                //    img: imageBase64
                // }));


                merge(this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity[this.currentImgIndex[2]], {
                  img: imageBase64,
                  raw: _this.h5_url_to_blob(imageBase64),
                })

                let listArr = this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity
                if (listArr.length < 6&& listArr[listArr.length-1].img) {  // 最多上传9张 不够添加空对象
                  this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity.push({
                    img: '',
                    raw: null,
                    name: '',
                  })
                }

                
                
            }
          });
        },
        fail: (error) => {
          console.log(error);
        }
      });
    },
    h5_url_to_blob(url) {
      let arr = url.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
  }
};
</script>
<style scoped lang="scss">
.perform-task-main {
  width: 100vw;
  height: 100vh;
  background: #F2F6FA;
  overflow: hidden;

  .task-head {
    box-shadow: 0px 4px 10px #ccc;
    span {
      color: #01a7f0;
    }
    .van-cell__label {
      color: #aaa;
    }
    .status {
      transform: rotate(45deg);
      font-size: 300;
      display: flex;
      align-items: center;
    }
  }

  .van-preview-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .van-swipe {
      width: 100%;
      height: 60%;
    }
    img {
      height: 90%;
    }
  }
  
  .main-container {
    height: calc(100vh - #{px2vh(200)});
    padding: px2vh(30) px2vw(30) px2vh(30) px2vw(30);
    overflow: auto;
    .small-img-btn {
      width: px2vw(60);
    }
    .item-title{
      color: #666666;
    }
    .mb20 {
      margin-bottom: px2vh(20);
    }
    .work-content {
      // height: 60vh;
      margin-bottom: px2vh(30);
    }
    
    .plate-title {
      margin-top: px2vh(30);
      margin-bottom: px2vh(27);
    }
    
    .info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      
      /deep/ .van-radio {
        margin-right: px2vw(139.5)
      }
      
      .image-list {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        .upload-button {
          width: px2vw(230);
          height: px2vw(230);
          flex-shrink: 0;
          background-size: 100% px2vw(230);
          margin: 0 calc((100% - #{px2vw(690)}) / 6) px2vh(60);
          position: relative;
          .delete-icon {
            position: absolute;
            top: px2vw(-20);
            right: px2vw(-20);
            width: px2vw(40);
            height: px2vw(40);
            background-color: rgba(0, 0, 0, 0.7);
            border-radius: 50%;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          img {
            width: px2vw(230);
            height: px2vw(230);
            border-radius: px2vw(6);
          }
        }
      }

      .remark-wrap {
        background-color: #FAFAFA;
        padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
        border-radius: px2vw(20);
        
        .remark-text {
          height: px2vh(150);
        }
      }

    }
  }
  footer {
    width: calc(100vw - #{px2vw(60)});
    display: flex;
    .van-button {
      flex: 1;
      margin: px2vh(40) px2vw(40);
      height: px2vh(100);
      color: #fff;
      background-color: #417ADC;
      border: 1px solid #417ADC;
      border-radius: px2vh(60);
    }
  }
  
}
 
</style>